package com.dcy.znoa.controller.publiz;

import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.publiz.model.company.*;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.publiz.Company;
import com.dcy.znoa.service.publiz.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;
import static com.dcy.znoa.common.util.pojo.JsonCommon.UPDATE_ERROR_CODE;

/**
 * @author pengyu
 */
//企业 controller
@Slf4j
@Controller
@RequestMapping("company")
public class CompanyController extends BaseController {
    @Autowired
    CompanyService companyService;

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectList")
    public JsonForList selectList(@Valid SelectCompanyModel model) throws BusinessException, InvocationTargetException, IllegalAccessException {
        Oper oper = getCurrentUser();
        return companyService.selectList(oper, model);
    }

    //    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectById")
    public JsonCommon selectById(Integer compId) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if(compId==null){
            return  new JsonCommon("404","请输入公司id");
        }
        return companyService.selectById(compId);
    }

    //    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/insert")
    public JsonCommon insert(@Valid AddCompanyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        if (getCurrentUser() != null && getCurrentUser().getOperId() != null && getCurrentUser().getOperId() > 0) {
            model.setCreateOperId(getCurrentUser().getOperId());
        }
        Company cp = new Company();
        BeanUtils.copyProperties(cp, model);
        return companyService.insert(cp);
    }
    //pengyu modify 只按原型做功能，一般修改功能和逻辑删除功能用一个接口就好，没有批量更新或删除的功能就不做，
    //做加法而不是做减法
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/updateById")
    public JsonCommon updateById(@Valid UpdateCompanyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        model.setUpdateOperId(getCurrentUser().getOperId());
        Company cp = new Company();
        BeanUtils.copyProperties(cp, model);
        return companyService.updateById(cp);
    }

//    @AuthenticationAPI
//    @ResponseBody
//    @RequestMapping("/logicDeleteById")
//    public JsonCommon logicDeleteById(@Valid LogicDelCompanyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
//        if (bindingResult.hasErrors()){
//            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
//        }
//        model.setUpdateOperId(getCurrentUser().getOperId());
//        Company cp = new Company();
//        BeanUtils.copyProperties(cp, model);
//        return companyService.updateById(cp);
//    }

//    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/insertCompAndOper")
    public JsonCommon insertCompAndOper(@Valid AddCompAndOperModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        log.info("insertCompAndOper:" + model.toString());
        if (getCurrentUser() != null && getCurrentUser().getOperId() != null && getCurrentUser().getOperId() > 0) {
            model.setCreateOperId(getCurrentUser().getOperId());
        }
        Company cm = new Company();
        Oper op = new Oper();
        BeanUtils.copyProperties(cm, model);
        BeanUtils.copyProperties(op, model);
        return companyService.insertCompAndOper(cm, op);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/connectToEstate")//企业和物业绑定
    public JsonCommon connectToEstate(Long esId,String compIds) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (esId==null || StringUtils.isEmpty(compIds)){
            return  new JsonCommon("404","入参缺失");
        }
        Long operId =getCurrentUser().getOperId();
//        List<Long> listIds = Arrays.asList(compIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<String> listIds = null;
        try {
            listIds = Arrays.asList(compIds.split(","));
        } catch (Exception e) {
            e.printStackTrace();
            return  new JsonCommon("404","compIds 参数格式错误");
        }
        if(listIds==null || listIds.isEmpty()){//看看有没有可能执行到这里
            return  new JsonCommon("404","compIds 为空 ");
        }
        boolean result = companyService.connectToEstate(esId, operId ,listIds);
        if(result){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon(UPDATE_ERROR_CODE);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/untieToEstate")//企业和物业解绑
    public JsonCommon untieToEstate(String compIds) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (StringUtils.isEmpty(compIds)){
            return  new JsonCommon("404","入参缺失");
        }
        Long operId =getCurrentUser().getOperId();
//        List<Long> listIds = Arrays.asList(compIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<String> listIds = null;
        try {
            listIds = Arrays.asList(compIds.split(","));
        } catch (Exception e) {
            e.printStackTrace();
            return  new JsonCommon("404","compIds 参数格式错误");
        }
        if(listIds==null || listIds.isEmpty()){//看看有没有可能执行到这里
            return  new JsonCommon("404","compIds 为空 ");
        }
        boolean result = companyService.untieToEstate(operId ,listIds);
        if(result){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon(UPDATE_ERROR_CODE);
    }

    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/setValidFlag")//设置企业有效或无效  参数多于2个就用对象，反正就直接用参数
    public JsonCommon setValidFlag(Integer validFlag,String compIds) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (validFlag==null || validFlag <0 || validFlag >1){
            return  new JsonCommon("404","validFlag入参缺失或不为0或1");
        }
        Long operId =getCurrentUser().getOperId();
//        List<Long> listIds = Arrays.asList(compIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        List<String> listIds = null;
        try {
            listIds = Arrays.asList(compIds.split(","));
        } catch (Exception e) {
            e.printStackTrace();
            return  new JsonCommon("404","compIds 参数格式错误");
        }
        if(listIds==null || listIds.isEmpty()){//看看有没有可能执行到这里
            return  new JsonCommon("404","compIds 为空 ");
        }
        boolean result = companyService.setValidFlag(validFlag, operId ,listIds);
        if(result){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon(UPDATE_ERROR_CODE);
    }
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectNotInByEsId")//查询某个物业ID没关联的企业列表，按创建时间倒序    Long esId,String compName
    public JsonForList selectNotInByEsId(@Valid SelectNotInByEsIdModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonForList("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper oper = getCurrentUser();
        return new JsonForList(companyService.selectList(model));
    }


}
